<?php

/**
 * This is the model class for table "{{material_receipt}}".
 *
 * The followings are the available columns in table '{{material_receipt}}':
 * @property integer $id
 * @property integer $projectId
 * @property string $receiptDate
 * @property integer $merchantId
 * @property string $handler
 * @property string $note
 * @property string $token
 * @property integer $type
 * @property string $processingCost
 * @property string $transportationCost
 * @property string $discount
 * @property string $otherCost
 * @property integer $warehouseManagerId
 * @property integer $materialExpenseId
 * @property integer $priceCheckable
 * @property integer $altMode
 * @property string $createTime
 * @property integer $createUserId
 * @property string $updateTime
 * @property integer $updateUserId
 *
 * The followings are the available model relations:
 * @property Employee $warehouseManager
 * @property User $createUser
 * @property Merchant $merchant
 * @property Project $project
 * @property User $updateUser
 * @property MaterialExpense $materialExpense
 * @property MaterialReceiptItem[] $materialReceiptItems
 */
class MaterialReceipt extends CActiveRecord {
	/**
	 * Returns the static model of the specified AR class.
	 * @return MaterialReceipt the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public static function getPopularHandlers() {
		$id = __CLASS__ . '.handler.popular';
		$value = Yii::app()->cache->get($id);
		if ($value === false) {
			$criteria = new CDbCriteria();
			$criteria->distinct = true;
			$criteria->select = 'handler';
			$criteria->order = 'count(*) desc';
			$criteria->limit = 8;
			$criteria->group = 'handler';
			$criteria->with = array(
				'project',
				'warehouseManager',
				'createUser.employee'
			);
			$handlers = MaterialReceipt::model()->findAll($criteria);
			$value = array();
			foreach ($handlers as $handler) {
				$value[] = $handler->handler;
			}
			Yii::app()->cache->set($id, $value, YII_DEBUG ? 1 : 60);
		}
		return $value;
	}

	private static $_types = array(
		'1' => '发票',
		'2' => '收据',
		'3' => '白条',
		'10' => '其它'
	);

	public static function getTypes() {
		return self::$_types;
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return '{{material_receipt}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array(
				'projectId, receiptDate, handler, type, warehouseManagerId',
				'required'
			),
			array(
				'projectId, merchantId, type, warehouseManagerId, priceCheckable, altMode',
				'numerical',
				'integerOnly' => true
			),
			array(
				'handler, note, token',
				'length',
				'max' => 255
			),
			array(
				'processingCost, transportationCost, discount, otherCost',
				'length',
				'max' => 16
			),
			array(
				'processingCost, transportationCost, discount, otherCost',
				'numerical',
			),
			array(
				'processingCost, transportationCost, discount, otherCost, merchantId',
				'default',
				'value' => null,
			),
			array(
				'receiptDate',
				'date',
				'format' => 'yyyy-MM-dd',
			),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array(
				'id, projectId, receiptDate, merchantId, handler, note, type, processingCost, transportationCost, discount, otherCost, warehouseManagerId, createTime, createUserId, updateTime, updateUserId',
				'safe',
				'on' => 'search'
			),
		);
	}

	public function scopes() {
		return array(
			'altMode' => array(
				'condition' => $this->getTableAlias() . '.altMode=0',
			),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'materialExpense' => array(
				self::BELONGS_TO,
				'MaterialExpense',
				'materialExpenseId'
			),
			'warehouseManager' => array(
				self::BELONGS_TO,
				'Employee',
				'warehouseManagerId'
			),
			'createUser' => array(
				self::BELONGS_TO,
				'User',
				'createUserId'
			),
			'merchant' => array(
				self::BELONGS_TO,
				'Merchant',
				'merchantId'
			),
			'project' => array(
				self::BELONGS_TO,
				'Project',
				'projectId'
			),
			'updateUser' => array(
				self::BELONGS_TO,
				'User',
				'updateUserId'
			),
			'items' => array(
				self::HAS_MANY,
				'MaterialReceiptItem',
				'materialReceiptId',
				'with' => 'materialModel.material'
			),
			'itemsQuick' => array(
				self::HAS_MANY,
				'MaterialReceiptItem',
				'materialReceiptId',
				'limit' => 3,
				'with' => 'materialModel.material'
			),
			'itemCount' => array(
				self::STAT,
				'MaterialReceiptItem',
				'materialReceiptId',
			),
			'itemTotal' => array(
				self::STAT,
				'MaterialReceiptItem',
				'materialReceiptId',
				'select' => 'SUM(totalPrice)'
			),
		);
	}

	public function behaviors() {
		return array(
			'AuditableBehavior' => array(
				'class' => 'components.db.AuditableBehavior',
				'attributes' => 'projectId, receiptDate, merchantId, handler, note, type,'
					. 'processingCost, transportationCost, discount, otherCost, warehouseManagerId, priceCheckable, altMode, materialExpenseId'
			),
			'AuditStampBehavior' => array(
				'class' => 'components.db.AuditStampBehavior',
			),
			'IsRecentBehavior' => array(
				'class' => 'components.models.IsRecentBehavior',
			),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id' => 'ID',
			'projectId' => '项目',
			'receiptDate' => '日期',
			'merchantId' => '供货商',
			'handler' => '经办人',
			'note' => '备注',
			'token' => '票据号码',
			'type' => '类别',
			'processingCost' => '加工费',
			'transportationCost' => '运费',
			'discount' => '折扣',
			'otherCost' => '其它费用',
			'warehouseManagerId' => '库管',
			'priceCheckable' => '可查询价格',
			'altMode' => '公司模式',
			'createTime' => '创建时间',
			'createUserId' => '创建用户',
			'updateTime' => '更新时间',
			'updateUserId' => '更新用户',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria = new CDbCriteria;

		$criteria->compare('id', $this->id);
		$criteria->compare('projectId', $this->projectId);
		$criteria->compare('receiptDate', $this->receiptDate, true);
		$criteria->compare('merchantId', $this->merchantId);
		$criteria->compare('handler', $this->handler, true);
		$criteria->compare('note', $this->note, true);
		$criteria->compare('type', $this->type);
		$criteria->compare('processingCost', $this->processingCost, true);
		$criteria->compare('transportationCost', $this->transportationCost, true);
		$criteria->compare('discount', $this->discount, true);
		$criteria->compare('otherCost', $this->otherCost, true);
		$criteria->compare('warehouseManagerId', $this->warehouseManagerId);
		$criteria->compare('priceCheckable', $this->priceCheckable);
		$criteria->compare('altMode', $this->altMode);
		$criteria->compare('createTime', $this->createTime, true);
		$criteria->compare('createUserId', $this->createUserId);
		$criteria->compare('updateTime', $this->updateTime, true);
		$criteria->compare('updateUserId', $this->updateUserId);

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}

	public function getDisplayType() {
		if (isset(self::$_types[$this->type])) {
			return self::$_types[$this->type];
		}
		return null;
	}

	public function getTotalPrice() {
		$itemTotal = $this->getRelated('itemTotal');
		return $itemTotal + $this->processingCost + $this->transportationCost + $this->otherCost
			+ $this->discount;
	}

	public function getSummary() {
		$summary = sprintf('%s %s (%s) %s %s', $this->project->name, $this->receiptDate,
			$this->handler, ($this->merchantId ? $this->merchant->name : ''),
			Yii::app()->format->formatCurrency($this->getTotalPrice()));
		return $summary;
	}
}
